#!/usr/bin/env python2.5

##############################################################################################
#
#    LocateME! - Finds location of user in a specific building using contextual information
#    Copyright (C) <2009>  <Kattie Tay>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>
#
##############################################################################################


# Import packages
import subprocess
import re
import dbus
import gobject
import dbus.glib
import conic


# Initialize connection
def wlan_init_connection():
    bus = dbus.SystemBus(private=True)
    gobject.idle_add(wlan_connect)
    

# Create connection
# If device not connected, attempts to connect to default connection or 
# display connection selection dialog box
def wlan_connect():
    # Creates the connection object and attach the handler.
    connection = conic.Connection()
    assert(connection.request_connection(conic.CONNECT_FLAG_NONE))


# Check if device is connected to Internet
# If yes, return True, else, return False    
def wlan_check_conn_status():
    status = 1
    proc = subprocess.Popen('/sbin/iwlist wlan0 scan', shell=True, stdout=subprocess.PIPE)
    stdout_str = proc.communicate()[0]
    if stdout_str == "":
        status = 0
    return status


# Get essid of current wlan connection
def wlan_get_conn_essid():
    proc = subprocess.Popen('sudo iwconfig wlan0', shell=True, stdout=subprocess.PIPE)
    stdout_str = proc.communicate()[0]
    stdout_list = stdout_str.split('\n')
    for line in stdout_list:
        line = line.strip()
        match = re.search('ESSID:"(.*)"',line)
        if match:
            return match.group(1)
        
    
# Get wireless data corresponding to specified essid 
def wlan_get_iap_stats(loc_essid):  
    proc = subprocess.Popen('sudo iwlist wlan0 scan', shell=True, stdout=subprocess.PIPE)
    stdout_str = proc.communicate()[0]
    stdout_list = stdout_str.split('\n')
    essid=[]
    address=[]
    sig_level=[]
    
    # Extract essid, address and signal strength of each access point in list returned
    for line in stdout_list:
        line = line.strip()
        match = re.search('ESSID:"(.*)"', line)
        if match:
            essid.append(match.group(1))
        match = re.search('Address: (\S+)',line)
        if match:
            address.append(match.group(1))
        match = re.search('Signal level:(\S+) dBm',line)
        if match:
            sig_level.append(match.group(1))
    
    # Loop through list to find essid that matches specified essid
    # and extract corresponding address and signal strength
    results = []
    for i in range(0,len(essid)):
        if essid[i] == loc_essid:
            results.append([address[i], sig_level[i]])
    return results










